import {
    Route,
    Switch,
    Redirect
} from 'react-router-dom';

import { FC } from 'react';
import { RouteFace } from './../Types/index';

interface IProps{
    routes : Array<RouteFace>
}

const RouterView:FC<IProps> = ( { routes } )=>{
    if( !routes )
    {
        return null;
    }

    const RouteList = routes.filter(item=>item.component);
    const Redirects = routes.filter(item=>!item.component);

    return (
        <Switch>
            {
                RouteList.map( (item,index)=>{
                    return <Route 
                        key={index} 
                        path={item.path} 
                        render={ routerProps=>{
                            if( item.children )
                            {
                                return <item.component 
                                    { ...routerProps } 
                                    routes={ item.children }
                                />
                            }

                            return <item.component { ...routerProps } />
                        } }
                    />
                } )
            },
            {
                Redirects.map( ( { from , to } , index ) =>{
                    return <Redirect key={index} from={from} to={ to as string} />
                } )
            }
        </Switch>
    )
}

export default RouterView;